package com.ai.bitcoin.service.helper;

import com.ai.bitcoin.jpa.dao.ExtraRedeemCodeDao;
import com.ai.bitcoin.jpa.entity.ExtraRedeemCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class ExtraRedeemServiceHelper {

    @Autowired
    private ExtraRedeemCodeDao extraRedeemCodeDao;

    //更新兑换码状态
    @Transactional
    public int updateOne(String userOpenId,String id) {
        return  extraRedeemCodeDao.updateOne(userOpenId,id);
    }

    @Transactional
    public int improtFromExcel(MultipartFile file) throws IOException, InvalidFormatException {
        log.info("-------------------------------------开始导入excel数据----------------------------------------");
        InputStream ips = file.getInputStream();
        Workbook wb = null;
        if (file.getOriginalFilename().toLowerCase().endsWith(".xls")) {
            wb = new HSSFWorkbook(ips);
        } else if (file.getOriginalFilename().toLowerCase().endsWith(".xlsx")) {
            wb = new XSSFWorkbook(ips);
        }
        Sheet sheet = wb.getSheetAt(0);
        int rowNum = sheet.getPhysicalNumberOfRows();
        List<ExtraRedeemCode> list = new ArrayList<>();
        for (int i = 0; i < rowNum; i++) {
            Row row = sheet.getRow(i);
            ExtraRedeemCode extraRedeemCode = new ExtraRedeemCode();
            extraRedeemCode.setUserOpenId("");
            extraRedeemCode.setUpdateTime(new Date());
            extraRedeemCode.setState(0);
            extraRedeemCode.setCreateTime(new Date());
            extraRedeemCode.setIsActive(1);
            extraRedeemCode.setCode(row.getCell(0).getStringCellValue());
            extraRedeemCode.setRemark(row.getCell(1).getStringCellValue());

            list.add(extraRedeemCode);
        }
        List<ExtraRedeemCode> result = extraRedeemCodeDao.saveAll(list);
        log.info("-------------------------------------导入excel数据结束----------------------------------------");

        return result.size();
    }





}
